﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace WPFClient
{
    /// <summary>
    /// Interaction logic for Start.xaml
    /// </summary>
    public partial class Start : Page
    {
        public ChatClient client; //client for communicating with server
       
        public delegate void ConnectedHandler();
        public event ConnectedHandler Connected;
        
        public delegate void LoggedInHandler();
        public event LoggedInHandler LoggedIn;

        public delegate void NewAccountRequestHandler(); 
        public event NewAccountRequestHandler NewAccountRequest;
        //send signals that connection to server was made, log in was successful or that new account button was pressed respectively
        public Start()
        {
            InitializeComponent();
            try
            {
                FileStream stream = new FileStream("username.txt", FileMode.Open, FileAccess.Read);
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] bytes = new byte[(int)stream.Length];
                int bytesRead = 0;
                bytesRead = stream.Read(bytes, 0,(int)stream.Length);
                stream.Close(); //reads from username.txt file
                if (bytesRead > 0) //if file is not empty
                {
                    textBox1.Text = encoder.GetString(bytes); //contents of file put in username box
                }


 
                FileStream pass_stream = new FileStream("password.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
                bytes = new byte[(int)pass_stream.Length];
                bytesRead = 0;
                bytesRead = pass_stream.Read(bytes, 0, (int)pass_stream.Length);
                pass_stream.Close(); //reads password from password.txt
                if (bytesRead > 0)
                {
                    passwordBox1.Password = encoder.GetString(bytes); //contents of file put in password box
                }
            }
            catch (Exception) { } // if there is any problem dont do anything, just return blank boxes, it doesn't matter
        }
        public void Connect()
        {
          //tries to connect to server
            try
            {
                client = new ChatClient(); //initializes client
                Connected(); //sends signal that connection was successful
            }
            catch (Exception) //if there is any problem
            {
                Connect(); //tries again
            }
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //log in button
            try
            {
            bool success; //whether logged in or not
            if (passwordBox1.Password.CompareTo("") != 0) //if password box is not empty
            {
                success = client.login(textBox1.Text, passwordBox1.Password); //try to log in with username and password given
                // and place the result of success/failure in the success boolean
            }
            else //if password box is empty
            {
                success = client.login(textBox1.Text, "null"); //try to log in while setting the password to be the word 'null' (this is done to avoid
                // problems associaed with sending empty strings up the stream)
            }
                if (success) //if login successful
                {
                    TextWriter writer = new StreamWriter("username.txt");
                    writer.Write(textBox1.Text);
                    writer.Close(); //save username given in file

                    TextWriter pass_writer = new StreamWriter("password.txt");
                    pass_writer.Write(passwordBox1.Password);
                    pass_writer.Close(); //save password in file
                    LoggedIn(); //sends signal to MainWindow that log in was successful
                }
                else //if log in failed
                {
                    textBlock3.Text = "Log in failed. Try again."; //inform user that log in failed so they can retype a new username/password
                }
            }
            catch (Exception) { //if error in connecting to server
                textBlock3.Text = "Could not connect to server. Try again later."; //sends error message and asks user to try again

            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            //when 'new account' button pressed
            NewAccountRequest(); //sends signal to MainWindow to navigate to new account page
        }
    }
}
